package com.topteam.application;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.util.AntPathMatcher;

import com.jfinal.plugin.activerecord.Db;

public class TopApplicationContext implements Serializable{

	private static final long serialVersionUID = -4900442681061305753L;

	private final Map<String, String> configMap = new HashMap<String, String>();
	
	private final Set<String> unAuthUrl = new HashSet<String>();
	
	private Set<String> authUrl;
	
	public void initialize(){
		//TODO 系统相关配置参数初始化
		System.out.println("系统相关配置参数初始化");
		
		//TODO 无需验证拦截的请求
		unAuthUrl.add("/security/login");
		unAuthUrl.add("/security/auth");
		unAuthUrl.add("/error/**");
		unAuthUrl.add("/caipiao/**");
		
		List<String> list = Db.query("select m.menuUrl from FrameMenu m");
		authUrl = new HashSet<String>(list);
	}
	
	public boolean needLoginIntercept(String actionKey){
		AntPathMatcher matcher = new AntPathMatcher();
		boolean excludes = true;
		for (String e : unAuthUrl) {
			if (matcher.match(e, actionKey)) {
				excludes = false;
				break;
			}
		}
		return excludes;
	}
	
	public boolean needSecurithIntercept(String actionKey){
		return authUrl.contains(actionKey);
	}
	
	
	public synchronized void update(String key, String value){
		if(configMap.containsKey(key)){
			configMap.remove(key);
		}
		configMap.put(key, value);
	}
	
	public String getValue(String key){
		return configMap.get(key);
	}
	
	private static TopApplicationContext instance = new TopApplicationContext();
	
	public static TopApplicationContext getInstance(){
		return instance;
	}
}
